package cn.deschen.biz.service.impl;

import cn.deschen.biz.domain.entity.AdRegion;
import cn.deschen.biz.domain.entity.AdUnitRegion;
import cn.deschen.biz.dto.unit.UnitEleDTO;
import cn.deschen.biz.mapper.AdRegionMapper;
import cn.deschen.biz.service.AdRegionService;
import cn.deschen.biz.service.AdUnitRegionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 地区 Feature 服务实现类
 * </p>
 *
 * @author deschen
 * @since 2021-06-16
 */
@Service
public class AdRegionServiceImpl extends ServiceImpl<AdRegionMapper, AdRegion> implements AdRegionService {

    @Autowired
    private AdUnitRegionService unitRegionService;

    public static final String REGION_SEPARATOR = ":";

    @Override
    public void batchUnitRel(Long unitId, Collection<Long> regionIds) {
        List<AdUnitRegion> unitRegionList = regionIds.stream().map(regionId -> {
            AdUnitRegion unitRegion = new AdUnitRegion();
            unitRegion.setUnitId(unitId);
            unitRegion.setRegionId(regionId);
            return unitRegion;
        }).collect(Collectors.toList());
        unitRegionService.saveBatch(unitRegionList);
    }

    @Override
    public Set<Long> listEleIdById(Long unitId) {
        QueryWrapper<AdUnitRegion> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(AdUnitRegion::getUnitId, unitId);
        Set<Long> regionIdSet = unitRegionService.list(wrapper).stream().map(AdUnitRegion::getRegionId).collect(Collectors.toSet());
        return regionIdSet;
    }

    @Override
    public List<Long> saveBatchRegion(Long unitId, Collection<UnitEleDTO> unitEleDTOS) {
        List<Long> regionIdList = new ArrayList<>();
        List<AdRegion> regionList = new ArrayList<>();
        unitEleDTOS.stream().forEach(ele -> {
            if (null == ele.getEleId()) {
                AdRegion region = new AdRegion();
                String eleName = ele.getEleName();
                String[] regionArr = eleName.split(REGION_SEPARATOR);
                region.setProvince(regionArr[0]);
                region.setCity(regionArr[1]);
                regionList.add(region);
            }else {
                regionIdList.add(ele.getEleId());
            }
        });
        saveBatch(regionList);
        regionIdList.addAll(regionList.stream().map(AdRegion::getId).collect(Collectors.toList()));
        return regionIdList;
    }
}
